﻿#ifndef __SS_THREAD_GROUP_H__
#define __SS_THREAD_GROUP_H__
#include "ssMsgEngine.h"

namespace StarSeeker
{

template<typename MSG_THREAD>
class ssThreadGroup
{
public:
	ssThreadGroup()
	{
		m_groupID = 0;
		m_num = 0;
		m_thread = 0;
	}
	ssThreadGroup(u32 num)
	{
		m_groupID = 0;
		m_num = 0;
		m_thread = 0;
		SetThreadNum(num);
	}
	virtual ~ssThreadGroup()
	{
		Exit();
		if (m_thread)
			delete[] m_thread;
	}

	//启动线程组
	void Start()
	{
		for (u32 i = 0; i < m_num; ++i)
		{
			m_thread[i].StartThread();
		}
	}
	//退出线程组
	void Exit()
	{
		for (u32 i = 0; i < m_num; ++i)
		{
			m_thread[i].ExitThread();
		}
	}
	//发送消息,指定哪根线程
	void PostMsg(u32 index, ssMsg_s &m)
	{
		if (index < m_num)
		{
			m_thread[index].PostMsg(m);
		}
	}
	void PostMsg(u32 index, u32 msgID, u32 subID, ulint param1, ulint param2, ulint param3)
	{
		ssMsg_s m = { msgID, subID, param1, param2, param3 };
		PostMsg(index, m);
	}
	//发送消息,取任务最少的线程
	void PostMsg(ssMsg_s &m)
	{
		u32 minCount = (u32)m_thread[0].GetMsgCount();
		u32 minIndex = 0;
		for (u32 i = 1; i < m_num; ++i)
		{
			u32 tmp = (u32)m_thread[i].GetMsgCount();
			if (tmp < minCount)
			{
				minIndex = i;
				minCount = tmp;
			}
		}
		m_thread[minIndex].PostMsg(m);
	}
	void PostMsg(u32 msgID, u32 subID, ulint param1, ulint param2, ulint param3)
	{
		ssMsg_s m = { msgID, subID, param1, param2, param3 };
		PostMsg(m);
	}
	//设置线程数，必须在线程未启动状态
	bool SetThreadNum(u32 num)
	{
		if (!m_thread && num>0 && num<1024)
		{
			m_num = num;
			m_thread = new MSG_THREAD[m_num];
			return true;
		}
		return false;
	}
	//设置线程数组，必须在线程未启动状态
	bool SetThreads(u32 num, MSG_THREAD* pThreads)
	{
		if (!m_thread && num > 0 && num < 1024)
		{
			m_num = num;
			m_thread = pThreads;
			return true;
		}
		return false;
	}
protected:
	MSG_THREAD	*	m_thread;
	u32				m_num;
public:
	u32				m_groupID;
};


}
#endif
